using System;
using Csla;
using Ent.AccesoDatos;
using System.Collections.Generic;
using System.Data;
using EntGuayasSLA.BL.Listas.Criterias;

namespace EntGuayasSLA.BL.Licenciamiento
{
    [Serializable]
    public class Persona : BusinessBase<Persona>
    {
        #region Business Methods

        public static readonly PropertyInfo<Guid> IdProperty = RegisterProperty<Guid>(p => p.Id);
        public Guid Id
        {
            get { return GetProperty(IdProperty); }
            set { SetProperty(IdProperty, value); }
        }
        public static readonly PropertyInfo<string> ParroquiaIdProperty = RegisterProperty<string>(c => c.ParroquiaId);
        public string ParroquiaId
        {
            get { return GetProperty(ParroquiaIdProperty); }
            set { SetProperty(ParroquiaIdProperty, value); }
        }

        public static readonly PropertyInfo<string> IdentificacionProperty = RegisterProperty<string>(c => c.Identificacion);
        public string Identificacion
        {
            get { return GetProperty(IdentificacionProperty); }
            set { SetProperty(IdentificacionProperty, value); }
        }

        public static readonly PropertyInfo<string> NombreProperty = RegisterProperty<string>(c => c.Nombre);
        public string Nombre
        {
            get { return GetProperty(NombreProperty); }
            set { SetProperty(NombreProperty, value); }
        }

        public static readonly PropertyInfo<string> ApellidoProperty = RegisterProperty<string>(c => c.Apellido);
        public string Apellido
        {
            get { return GetProperty(ApellidoProperty); }
            set { SetProperty(ApellidoProperty, value); }
        }

        public static readonly PropertyInfo<string> DireccionProperty = RegisterProperty<string>(c => c.Direccion);
        public string Direccion
        {
            get { return GetProperty(DireccionProperty); }
            set { SetProperty(DireccionProperty, value); }
        }

        public static readonly PropertyInfo<string> EmailProperty = RegisterProperty<string>(c => c.Email);
        public string Email
        {
            get { return GetProperty(EmailProperty); }
            set { SetProperty(EmailProperty, value); }
        }
        public static readonly PropertyInfo<string> NacionalidadProperty = RegisterProperty<string>(c => c.Nacionalidad);
        public string Nacionalidad
        {
            get { return GetProperty(NacionalidadProperty); }
            set { SetProperty(NacionalidadProperty, value); }
        }
        public static readonly PropertyInfo<string> CertificadoProperty = RegisterProperty<string>(c => c.Certificado);
        public string Certificado
        {
            get { return GetProperty(CertificadoProperty); }
            set { SetProperty(CertificadoProperty, value); }
        }
        public static readonly PropertyInfo<string> CertificadoClaveProperty = RegisterProperty<string>(c => c.CertificadoClave);
        public string CertificadoClave
        {
            get { return GetProperty(CertificadoClaveProperty); }
            set { SetProperty(CertificadoClaveProperty, value); }
        }
        #endregion

        #region Business Rules
        protected override void AddBusinessRules()
        {
            // TODO: add validation rules
            base.AddBusinessRules();

            //BusinessRules.AddRule(new Rule(IdProperty));
        }
        private static void AddObjectAuthorizationRules()
        {
            // TODO: add authorization rules
            //BusinessRules.AddRule(...);
        }
        #endregion

        #region Factory Methods
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_identificacion"></param>
        /// <param name="_id">Id de persona</param>
        /// <returns></returns>
        public static bool VerificarIdentificacion(string _identificacion,string _id,string _ruc)
        {
            return ExisteIdentificacionCommand.Execute(_identificacion,_id,_ruc);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_correo"></param>
        /// <param name="_id">Id de persona</param>
        /// <returns></returns>
        public static int VerificarEmail(string _correo,string _id)
        {
            return ExisteEmailCommand.Execute(_correo, _id);
        }
        public static Persona NewEditableRoot()
        {
            return DataPortal.Create<Persona>();
        }

        public static Persona GetEditableRoot(PersonaCriteria cedula)
        {
            return DataPortal.Fetch<Persona>(cedula);
        }
        public static Persona GetEditableRoot(string idUser)
        {
            return DataPortal.Fetch<Persona>(idUser);
        }
        public static Persona GetEditableRoot(Guid id)
        {
            return DataPortal.Fetch<Persona>(id);
        }

        public static void DeleteEditableRoot(Guid id)
        {
            DataPortal.Delete<Persona>(id);
        }

        private Persona()
        { /* Require use of factory methods */ }

        #endregion

        #region Data Access

        [RunLocal]
        protected override void DataPortal_Create()
        {
            // TODO: load default values
            // omit this override if you have no defaults to set
            base.DataPortal_Create();
        }
        private void DataPortal_Fetch(PersonaCriteria criteria)
        {
            var accesoDatos = new DriveDataBase(TypeDataBase.PostgreSql);
            var parametros = new List<Parametro> { new Parametro("ec_identificacion", criteria.Cedula) };
            DataSet datos = accesoDatos.EjecutarDataSet("\"OBT_PERSONA_CED\"", parametros);
            if (datos.Tables[0].Rows.Count > 0)
            {
                LoadPropertys(datos);

            }
        }
        private void DataPortal_Fetch(string criteria)
        {
            var accesoDatos = new DriveDataBase(TypeDataBase.PostgreSql);
            var parametros = new List<Parametro> { new Parametro("ec_usr_login", criteria) };
            DataSet datos = accesoDatos.EjecutarDataSet("\"OBT_PERSONA_USER\"", parametros);
            if (datos.Tables[0].Rows.Count > 0)
            {
                LoadPropertys(datos);

            }
        }
        private void DataPortal_Fetch(Guid criteria)
        {
            var accesoDatos = new DriveDataBase(TypeDataBase.PostgreSql);
            var parametros = new List<Parametro> { new Parametro("ec_per_id", criteria.ToString()) };
            DataSet datos = accesoDatos.EjecutarDataSet("\"OBT_PERSONA\"", parametros);
            if (datos.Tables[0].Rows.Count > 0)
            {
                LoadPropertys(datos);         
               
            }
        }

        private void LoadPropertys(DataSet datos)
        {
            LoadProperty(IdProperty, Guid.Parse(datos.Tables[0].Rows[0]["per_id"].ToString()));
            LoadProperty(ParroquiaIdProperty, datos.Tables[0].Rows[0]["par_id"].ToString());
            LoadProperty(IdentificacionProperty, datos.Tables[0].Rows[0]["per_identificacion"].ToString());
            LoadProperty(NombreProperty, datos.Tables[0].Rows[0]["per_nombre"].ToString());
            LoadProperty(ApellidoProperty, datos.Tables[0].Rows[0]["per_apellido"].ToString());
            LoadProperty(DireccionProperty, datos.Tables[0].Rows[0]["per_direccion"].ToString());
            LoadProperty(EmailProperty, datos.Tables[0].Rows[0]["per_email"].ToString());
            LoadProperty(NacionalidadProperty, datos.Tables[0].Rows[0]["per_nacionalidad"].ToString());
            LoadProperty(CertificadoProperty, datos.Tables[0].Rows[0]["per_certificado"].ToString());
            LoadProperty(CertificadoClaveProperty, datos.Tables[0].Rows[0]["per_cer_clave"].ToString());
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_Insert()
        {
            var accesoDatos = new DriveDataBase(TypeDataBase.PostgreSql);
            var parametros = new List<Parametro> { 
                new Parametro("ec_per_id", ReadProperty(IdProperty)),
                new Parametro("ec_par_id", ReadProperty(ParroquiaIdProperty)),
                new Parametro("ec_per_identificacion", ReadProperty(IdentificacionProperty)),
                new Parametro("ec_per_nombre", ReadProperty(NombreProperty)),
                new Parametro("ec_per_apellido", ReadProperty(ApellidoProperty)),
                new Parametro("ec_per_direccion", ReadProperty(DireccionProperty)),
                new Parametro("ec_per_email", ReadProperty(EmailProperty)),
                new Parametro("ec_per_nacionalidad", ReadProperty(NacionalidadProperty))
            };
            accesoDatos.EjecutarQuery("\"INS_PERSONA\"", parametros);
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_Update()
        {
            var accesoDatos = new DriveDataBase(TypeDataBase.PostgreSql);
            var parametros = new List<Parametro> { 
                new Parametro("ec_per_id", ReadProperty(IdProperty)),
                new Parametro("ec_par_id", ReadProperty(ParroquiaIdProperty)),
                new Parametro("ec_per_identificacion", ReadProperty(IdentificacionProperty)),
                new Parametro("ec_per_nombre", ReadProperty(NombreProperty)),
                new Parametro("ec_per_apellido", ReadProperty(ApellidoProperty)),
                new Parametro("ec_per_direccion", ReadProperty(DireccionProperty)),
                new Parametro("ec_per_email", ReadProperty(EmailProperty)),
                new Parametro("ec_per_nacionalidad", ReadProperty(NacionalidadProperty)),
                new Parametro("ec_per_certificado", ReadProperty(CertificadoProperty)),
                 new Parametro("ec_per_cer_clave", ReadProperty(CertificadoClaveProperty))
            };
            accesoDatos.EjecutarQuery("\"ACT_PERSONA\"", parametros);
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(this.Id);
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        private void DataPortal_Delete(Guid criteria)
        {
            var accesoDatos = new DriveDataBase(TypeDataBase.PostgreSql);
            var parametros = new List<Parametro> { 
                new Parametro("ec_per_id", ReadProperty(IdProperty))
            };
            accesoDatos.EjecutarQuery("\"ELI_PERSONA\"", parametros);
        }

        #endregion
    }
    [Serializable]
    public class ExisteEmailCommand : CommandBase<ExisteEmailCommand>
    {
        private string _email;
        private string _id;
        #region Authorization Methods

        public static bool CanExecuteCommand()
        {
            // TODO: customize to check user role
            //return Csla.ApplicationContext.User.IsInRole("Role");
            return true;
        }

        #endregion

        #region Factory Methods

        public static int Execute(string usuario,string id)
        {
            if (!CanExecuteCommand())
                throw new System.Security.SecurityException("Not authorized to execute command");

            ExisteEmailCommand cmd = new ExisteEmailCommand(usuario,id);
            cmd.BeforeServer();
            cmd = DataPortal.Execute<ExisteEmailCommand>(cmd);
            cmd.AfterServer();
            return cmd.Result;
        }

        private ExisteEmailCommand(string _correo,string id)
        { /* require use of factory methods */
            _email = _correo;
            _id = id;
            _result = 0;
        }

        #endregion

        #region Client-side Code

        // TODO: add your own fields and properties
        int _result;

        public int Result
        {
            get { return _result; }
        }

        private void BeforeServer()
        {
            // TODO: implement code to run on client
            // before server is called
        }

        private void AfterServer()
        {
            // TODO: implement code to run on client
            // after server is called
        }

        #endregion

        #region Server-side Code

        protected override void DataPortal_Execute()
        {
            int numeroCorreo = 0; object valret;
            var accesoDatos = new DriveDataBase(TypeDataBase.PostgreSql);
            var parametros = new List<Parametro> { new Parametro("ec_email", _email),
            new Parametro("ec_per_id", _id)};
            try
            {

                valret = accesoDatos.EjecutarScalar("\"CMD_COMPROBAR_CORREO\"", parametros);

                int.TryParse(valret.ToString(), out numeroCorreo);
                _result = numeroCorreo;
              
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion
    }
    [Serializable]
    public class ExisteIdentificacionCommand : CommandBase<ExisteIdentificacionCommand>
    {
        private string _identificacion;
        private string _id;
        private string _cedula;
        #region Authorization Methods

        public static bool CanExecuteCommand()
        {
            // TODO: customize to check user role
            //return Csla.ApplicationContext.User.IsInRole("Role");
            return true;
        }

        #endregion

        #region Factory Methods

        public static bool Execute(string identificacion,string id,string ced)
        {
            if (!CanExecuteCommand())
                throw new System.Security.SecurityException("Not authorized to execute command");

            ExisteIdentificacionCommand cmd = new ExisteIdentificacionCommand(identificacion, id, ced);
            cmd.BeforeServer();
            cmd = DataPortal.Execute<ExisteIdentificacionCommand>(cmd);
            cmd.AfterServer();
            return cmd.Result;
        }

        private ExisteIdentificacionCommand(string identificacion, string id, string _ced)
        { 
            /* require use of factory methods */
            _identificacion = identificacion;
            _id = id;
            _cedula = _ced;
            _result = false;
        }

        #endregion

        #region Client-side Code

        // TODO: add your own fields and properties
        bool _result;

        public bool Result
        {
            get { return _result; }
        }

        private void BeforeServer()
        {
            // TODO: implement code to run on client
            // before server is called
        }

        private void AfterServer()
        {
            // TODO: implement code to run on client
            // after server is called
        }

        #endregion

        #region Server-side Code

        protected override void DataPortal_Execute()
        {
            int numeroidentificacion = 0; object valret;
            var accesoDatos = new DriveDataBase(TypeDataBase.PostgreSql);
            var parametros = new List<Parametro> { 
                new Parametro("ec_per_identificacion", _identificacion),
                new Parametro("ec_per_id", _id),
                new Parametro("ec_pro_ruc",_cedula)
            };
            try
            {

                valret = accesoDatos.EjecutarScalar("\"CMD_COMPROBAR_IDENTIFICACION\"", parametros);

                int.TryParse(valret.ToString(), out numeroidentificacion);
                if (numeroidentificacion == 0)
                    _result = true;
                else
                    _result = false;
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion
    }

}
